package com.sun.gis.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.coverage.grid.io.GridCoverage2DReader;
import org.geotools.coverage.grid.io.GridFormatFinder;
import org.geotools.geometry.Envelope2D;
import org.geotools.referencing.CRS;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.parameter.ParameterValueGroup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

@Api(tags = "地图切片wmts访问接口")
@RestController
public class TileController {

    @Value("${tiles.inputPath}")
    private String inputPath;

    @Value("${tiles.outputPath}")
    private String outputPath;

    @ApiOperation(value = "wmts切片访问接口")
    @GetMapping("/wmts")
    public ResponseEntity<InputStreamResource> getTile(@RequestParam("layers") String layer,
                                                       @RequestParam String tileMatrix,
                                                       @RequestParam String tileRow,
                                                       @RequestParam String tileCol) throws Exception {

        String inputTif = inputPath + layer + ".tif";
        String outputTile = outputPath + "tile_" + layer + "_" + tileMatrix + "_" + tileRow + "_" + tileCol + ".png";

        // 加载GeoTIFF
        File geotiff = new File(inputTif);
        AbstractGridFormat format = GridFormatFinder.findFormat(geotiff);
        GridCoverage2DReader reader = format.getReader(geotiff);

        // 计算瓦片的地理范围
        int tileSize = 256;
        double minx = Double.parseDouble(tileCol) * tileSize;
        double maxx = (Double.parseDouble(tileCol) + 1) * tileSize;
        double miny = Double.parseDouble(tileRow) * tileSize;
        double maxy = (Double.parseDouble(tileRow) + 1) * tileSize;

        Envelope2D envelope = new Envelope2D(CRS.decode("EPSG:3857"), minx, miny, maxx - minx, maxy - miny);

        // 设置读取参数
        ParameterValueGroup params = reader.getFormat().getReadParameters();
        params.parameter(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString()).setValue(envelope);

        GridCoverage2D coverage = reader.read(new GeneralParameterValue[]{params});

        // 转换为BufferedImage
        BufferedImage image = new BufferedImage(tileSize, tileSize, BufferedImage.TYPE_INT_ARGB);
        image.createGraphics().drawRenderedImage(coverage.getRenderedImage(), null);

        // 写入文件
        ImageIO.write(image, "PNG", new File(outputTile));

        File file = new File(outputTile);
        if (!file.exists()) {
            return ResponseEntity.status(500).build();
        }

        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                .contentType(MediaType.IMAGE_PNG)
                .contentLength(file.length())
                .body(resource);
    }
}